﻿var chatManger = function (layim, room) {
    var connection = new signalR.HubConnectionBuilder().withUrl('/im/chatHub').build();

    // 发送消息
    layim.on('sendMessage',
        function (res) {
            connection.invoke('SendMessage', 'chat', JSON.stringify(res))
                .catch(function (err) {

                });
        });

    var handlers = {
        chat: function (data) {
            layim.getMessage(data);
        },
        addList: function (data) {
            layim.addList(data);
        }
    }

    connection.on('ReceiveMessage', function (type, json) {
        console.log('received: ' + type);
        var msg = JSON.parse(json);
        console.log(msg);
        var handler = handlers[type];
        if (handler) {
            handler(msg);
        } else {
            console.warn('no handler for event: ' + type);
        }
    });

    connection.start().then(function () {
        console.log('连接服务器成功');
        if (room) {
            layim.getMessage({
                system: true,
                id: room.id,
                type: room.type,
                content: '请文明发言，遵守各项法律法规。不要随意透露账号密码、银行账号等信息。'
            });
            layim.getMessage({
                system: true,
                id: room.id,
                type: room.type,
                content: '请稍后！正在为您分配客服人员'
            });
        }
    }).catch(function (err) {
        return console.error('连接服务器失败: ' + err.toString());
    });
};